package com.edol.painting.data;

import android.content.Context;
import android.graphics.BitmapFactory;

import com.doodle.common.utils.AsyncDataLoader;
import com.doodle.common.utils.Future;
import com.doodle.common.utils.FutureListener;
import com.doodle.common.utils.SDCardHelper;
import com.doodle.common.utils.ThreadPool;
import com.edol.painting.data.PaintingDatabase.PaintingEntry;
import com.edol.painting.utils.PainterUtils;

import java.io.File;
import java.util.List;

public class PaintingListLoader extends AsyncDataLoader<List<PaintingEntry>> implements PaintingDatabase.PaintingChangedListener {
	
	private boolean mIsCheckBitmapDamage = true;

	public PaintingListLoader(Context context) {
		super(context);
	}

	@Override
	public List<PaintingDatabase.PaintingEntry> loadInBackground() {
		if (!SDCardHelper.getInstance().isMounted()) {
			return null;
		}
		PaintingDatabase.getInstance().generateSamplePainting(getContext());
		PaintingDatabase.getInstance().waitForSavingDone();
		return getShowAllPaintings(PaintingDatabase.getInstance().getAllPaintings());
	}

	protected void registerObserver() {
		PaintingDatabase.getInstance().addPaintingChangeListener(this);
    }
    
    protected void unregisterObserver() {
    	PaintingDatabase.getInstance().removePaintingChangeListener(this);
    }
    
    private List<PaintingDatabase.PaintingEntry> getShowAllPaintings(List<PaintingDatabase.PaintingEntry> list) {
    	if (mIsCheckBitmapDamage && list.size() > 0) {
    		final PaintingDatabase.PaintingEntry pe = list.get(0);
    		if (!PaintingDatabase.getInstance().checkInitBitmap(new File(pe.mDirectory).getName()) && pe.mLayer) {
	    		final String str = pe.mDirectory.substring(0, pe.mDirectory.length() - 4);
	    		if (!PainterUtils.checkPaintingEntry(pe)) {
	    			ThreadPool.getInstance().submit(new ThreadPool.Job<Boolean>() {
	    				@Override
	    				public Boolean run(ThreadPool.JobContext jc) {
                            BitmapFactory.Options op = new BitmapFactory.Options();
                            op.inJustDecodeBounds = true;
                            BitmapFactory.decodeFile(str + "-2.png", op);
                            boolean b = op.outWidth != 0 || op.outHeight != 0;
	    					return b;
	    				}
	    			}, new FutureListener<Boolean>() {
	    				@Override
	    				public void onFutureDone(Future<Boolean> future) {
                            if (!future.get()) {
                                PaintingDatabase.getInstance().deleteByIds(new long[] { pe.mId }, null);
                            }
	    				}
	    			});
	    		} else {
	    			PaintingDatabase.getInstance().deleteByIds(new long[] { pe.mId }, null);
	    		}
    		}
    	}
    	mIsCheckBitmapDamage = false;
    	return list;
    }
    
	@Override
	public void onPaintingListChanged() {
		forceLoad();
	}

}
